package com.xiaojie.rabbitmq.tx;

import com.rabbitmq.client.*;
import com.xiaojie.rabbitmq.MyConnection;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

/**
 * @Description: 事务模拟消费者
 * 如果不该为手动应达模式，那么事务开启对消费者没有影响
 * @author: xiaojie
 * @date: 2021.09.28
 */
public class Txconsumer {

    private static final String QUEUE_NAME = "myqueue";

    public static void main(String[] args) throws IOException, TimeoutException {
        // 1.创建我们的连接
        Connection connection = MyConnection.getConnection();
        // 2.创建我们通道
        Channel channel = connection.createChannel();
        channel.txSelect();//开启事务
        DefaultConsumer defaultConsumer = new DefaultConsumer(channel) {
            @Override
            public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
                String msg = new String(body, "UTF-8");
                //设置手动应答
                channel.basicAck(envelope.getDeliveryTag(), true);
                System.out.println("消费消息msg:" + msg+"手动应答："+envelope.getDeliveryTag());
                channel.txCommit(); //消费者开启事务，必须要提交事务之后，消息才会从队列中移除，否则不移除。
            }
        };
        // 3.创建我们的监听的消息 false 关闭自动确认模式
        channel.basicConsume(QUEUE_NAME, false, defaultConsumer);

    }
}
